package server.core;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import entity.Reply;
import entity.Request;
import entity.UserInfo;

public class RequestHandler implements Runnable {
	private Socket cs;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	private Reply rep;
	private Request req;
	private ConnectionListener cl;

	public RequestHandler(Socket s, ConnectionListener cl) throws IOException {
		cs = s;
		this.cl = cl;
		ois = new ObjectInputStream(cs.getInputStream());
		oos = new ObjectOutputStream(cs.getOutputStream());
	}

	public void run() {
		try {
			req = (Request) ois.readObject();
			switch (req.getType()) {
			case 0:
				rep = new Reply(0);
				rep.setRegister_isSuccessful(true);
				rep.setRegister_isSuccessful(ServerCore.addUser(req
						.getRegister_usrinfo()));
				break;

			case 1:
				rep = new Reply(1);
				UserInfo usrinfo1 = ServerCore.login(req.getLogin_name(),
						req.getLogin_pwd());
				if (usrinfo1 == null)
					rep.setLogin_isSuccessful(false);
				else {
					rep.setLogin_isSuccessful(true);
					rep.setLogin_usrinfo(usrinfo1);
				}
				break;

			case 2:
				rep = new Reply(2);
				rep.setSearchUser_vui(ServerCore.findUser(
						req.getSearchUser_s_uid(),
						req.getSearchUser_t_nickname()));
				break;

			case 3:
				rep = new Reply(3);
				rep.setAddFriend_isSuccessful(ServerCore.addFriend(
						req.getAddFriend_s_uid(), req.getAddFriend_t_uid()));
				break;

			case 4:
				rep = new Reply(4);
				rep.setPublishNewsFeed_isSuccessful(ServerCore
						.publishNewsfeed(req.getTxtinfo()));
				break;
			case 5:
				rep = new Reply(5);
				rep.setCheckNewsFeed_vti(ServerCore.viewNewsfeed(req
						.getCheckNewsFeed_uid()));
				break;
			default:
				break;
			}
			// System.out.println(rep.getType());
			oos.writeObject(rep);
			cs.close();

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		cl.freethreadCount++;
	}
}
